import {message} from 'antd';

// 仅限字符串输入
export const getStringWithoutSpace = (e: any) => {
    if (
        e?.nativeEvent?.inputType === 'insertCompositionText' &&
        e?.nativeEvent?.data?.trim() === ''
    ) {
        // 判断若正在输入中文且没有输入完成则不处理
        return e.target.value;
    }
    return e.target.value.replace(/(^\s*)|(\s*$)/g, '');
};


export function downloadFile(url: string, fileName = 'download') {
    const element = document.createElement('a');
    element.style.display = 'none';
    element.href = url;
    element.setAttribute('download', fileName);
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
}


/**
 * @description: 将秒数转化为时分秒
 * @param {Number} seconds 秒数
 * @return {*}
 */
export const formatSecond = (seconds: number) => {
    if (typeof seconds !== 'number') {
        return '';
    }

    const hS = 3600;
    const mS = 60;

    const h = Math.floor(seconds / hS);
    const m = Math.floor((seconds - hS * h) / 60);
    const s = Math.floor(seconds - hS * h - mS * m);
    let result = s + "''";
    if (m > 0) {
        result = m + "'" + result;
    }
    if (h > 0) {
        result = h + ':' + result;
    }
    return result;
};

enum Unit {
    MB = 'MB',
    KB = 'KB',
}

type BeforeUploadOptions = {
    // 文件格式
    acceptType?: string[];
    maxSize?: {
        // 文件大小最大值
        size: number;
        // 文件大小最大值单位
        unit: 'MB' | 'KB';
    };
};


export const deconstructObject = (
    obj: Record<string, any>,
    keyName?: string,
): Record<string, any> => {
    if (obj) {
        return Object.keys(obj).reduce((all, currentKey) => {
            let str = '';
            if (keyName) {
                str = `${keyName}.${currentKey}`;
            } else {
                str = currentKey;
            }
            const val = obj[currentKey];
            if (typeof val === 'object' && isNaN(val.length)) {
                const data = deconstructObject(val, str);
                return {...all, ...data};
            } else {
                all[str] = val;
            }
            return all;
        }, {});
    }
    return {};
};
